package controller;

import com.alibaba.fastjson.JSON;
import entity.User;
import service.UserService;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(urlPatterns = "/user")
public class UserController extends BaseServlet{
    UserService userService=new UserService();
    public void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取前端传来的账号密码
        String userName=request.getParameter("userName");
        String password=request.getParameter("password");
        // sql语句
        String sql="select * from user where userName=? and password=?";
        User user=userService.login(sql,userName,password);
        /*如果user登录成功，将user对象保存在session中，
        因为session是全局对象，前后端可以实现数据共享*/
        if (user.getId()>0){
            request.getSession().setAttribute("user",user);
        }
        // 后端不再页面跳转，而是将user传输给前端，前端根据user是否为空判断登录成功与否
        PrintWriter printWriter=response.getWriter();
        // fastjson包
        printWriter.write(JSON.toJSONString(user));
        printWriter.close();
    }

    public void registry(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取前端传来的账号密码
        String userName=request.getParameter("userName");
        String password=request.getParameter("password");
        // sql语句
        String sql="insert into user values(null,?,?)";
        int count=userService.registry(sql,userName,password);
        PrintWriter printWriter=response.getWriter();
        // 转换为字符串
        printWriter.write(JSON.toJSONString(count));
        printWriter.close();
    }

    // 注销账号不用访问数据库
    public void loginOut(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int result=0;
        try {
            // 删除session中保存的账号密码信息
            request.getSession().removeAttribute("user");
            result=1;
        }catch (Exception e){

        }
        // 将结果返回给前端
        PrintWriter printWriter=response.getWriter();
        printWriter.write(JSON.toJSONString(result));
        printWriter.close();
    }
}
